<template>
  <div class="products">
    <van-dropdown-menu>
      <van-dropdown-item title="综合" disabled />
      <van-dropdown-item
        title="价格"
        v-model="price"
        :options="priceArr"
        @change="priceChange"
      />
      <van-dropdown-item
        title="分类"
        v-model="category"
        :options="filterCategory"
        @change="categoryChange"
      />
    </van-dropdown-menu>
    <Chanpin :goodsList="goodsList" v-if="this.goodsList.length>0" />
    <van-empty image="search" v-else description="暂无商品" />
  </div>
</template>

<script>
import Chanpin from "@/components/Chanpin.vue";
import { ProductsSearchApi } from "@/request/api";
export default {
  props: ["keyword"],
  data() {
    return {
      price: "desc",
      category: 0,
      priceArr: [
        { text: "价格由高到低", value: "desc" },
        { text: "价格由低到高", value: "asc" },
      ],
      // 产品列表的数组
      goodsList: [],
      filterCategory: [],
      // 页数
      page: 1,
      size: 20,
      // 价格排序，desc表示价格由高到低，asc表示价格由低到高
      order: "desc",
      categoryId: 0,
      // 按照id或price排序
      sort: "id",
    };
  },
  components: {
    Chanpin,
  },
  created() {
    this.productSearch(); // 调用产品搜索函数
  },
  methods: {
    // 封装了一个产品搜索的函数
    productSearch() {
      ProductsSearchApi({
        keyword: this.keyword,
        page: this.page,
        size: this.size,
        order: this.order,
        categoryId: this.categoryId,
        sort: this.sort,
      }).then((res) => {
        if (res.errno === 0) {
          let { goodsList, filterCategory } = res.data;
          this.goodsList = goodsList;
          // filterCategory需要把name替换成text,把id替换成value
          let filterCategory1 = JSON.parse(
            JSON.stringify(filterCategory)
              .replace(/name/g, "text")
              .replace(/id/g, "value")
          );
          this.filterCategory = filterCategory1;
          this.filterCategory.map((item) => {
            if (item.checked) {
              this.category = item.value;
            }
          });
        }
      });
    },
    // 分类切换
    categoryChange(value) {
      this.categoryId = value; // categoryId
      this.productSearch(); // 调用产品搜索函数
    },
    // 价格切换
    priceChange(value) {
      this.order = value;
      this.sort = "price";  // 把排序的形式按照价格来
      this.productSearch(); // 调用产品搜索函数
    },
  },
};
</script>
 
<style lang = "less" scoped>
.products {
  background: #fff;
  min-height: calc(100vh - 54px);
}
</style>